import 'package:flutter/material.dart';

class TstRefrsh extends StatefulWidget {
  @override
  _TstRefrshSate createState() => _TstRefrshSate();
}

class _TstRefrshSate extends State<TstRefrsh> {
  final ScrollController _scrollController = new ScrollController(); //滚动监听
  bool disposed = false;
  final GlobalKey<RefreshIndicatorState> refreshKey = new GlobalKey();

  int pageSize = 30;
  List<String> dataList = List();

  Future<void> onRefresh() async {
    await Future.delayed(Duration(seconds: 2));
    dataList.clear();
    for (int i = 0; i < pageSize; i++) {
      dataList.add("refresh");
    }
    if (disposed) {
      return;
    }
    setState(() {});
  }

  Future<void> loadMore() async {
    await Future.delayed(Duration(seconds: 2));
    for (int i = 0; i < pageSize; i++) {
      dataList.add("loadmore");
    }
    if (disposed) {
      return;
    }
    setState(() {});
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _scrollController.addListener(() {
      ///判断当前滑动位置是不是到达底部，触发加载更多回调
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        loadMore();
      }
    });
    Future.delayed(Duration(seconds: 0), () {
      refreshKey.currentState.show();
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
        appBar: AppBar(
          title: Text('下拉刷新'),
          centerTitle: true,
        ),
        body: Container(
          child: RefreshIndicator(
            key: refreshKey,
            onRefresh: onRefresh,
            child: ListView.builder(
              ///保持ListView任何情况都能滚动，解决在RefreshIndicator的兼容问题。
              physics: const AlwaysScrollableScrollPhysics(),

              ///根据状态返回
              itemBuilder: (context, index) {
                if (index == dataList.length) return _itemLoadMoreWiget();
                return _itemAddWiget(index);
              },

              ///根据状态返回数量
              itemCount: (dataList.length >= pageSize)
                  ? dataList.length + 1
                  : dataList.length,

              ///滑动监听
              controller: _scrollController,
            ),
          ),
        ));
  }

  //添加行
  Widget _itemAddWiget(int index) {
    return Card(
      child:  Container(
        height: 60,
        alignment: Alignment.centerLeft,
        padding: EdgeInsets.only(left: 10),
        child:  Text("Row ${dataList[index]} $index"),
      ),
    );
  }

  //添加加载更多
  Widget _itemLoadMoreWiget() {
    return Container(
      // color: Colors.blueGrey,
      child: Row(
        children: <Widget>[
          Expanded(
            child: Text(''),
          ),
          Container(
            height: 30,
            width: 30,
            child: CircularProgressIndicator(
              strokeWidth: 2,
            ),
            alignment: Alignment.center,
          ),
          Padding(
              padding: EdgeInsets.only(left: 10),
              child: Text(
                '加载更多',
                style: TextStyle(
                  color: Colors.blueGrey,
                ),
              )),
          Expanded(
            child: Text(''),
          ),
        ],
      ),
    );
  }
}
